﻿using Application.Common.Interface;
using Core.Persistence;
using Domain.Model.Options;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace Core
{
    public static class DependencyInjection
    {

        public static IServiceCollection AddConfigs(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<OptionConfig>(configuration.GetSection("ContextStrings"));
            return services;
        }

        public static IServiceCollection AddDbContext(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext<WebScraperDbContext>(options => options.UseSqlite(configuration.GetConnectionString("WebScraperDbContext")));
            return services;
        }

        public static IServiceCollection AddRepository(this IServiceCollection services, IEnumerable<Assembly> assemblies)
        {
            var baseType = typeof(IRepository);

            var types = assemblies
                .SelectMany(a => a.DefinedTypes)
                .Select(type => type.AsType())
                .Where(x => x != baseType && baseType.IsAssignableFrom(x)).ToArray();
            var implementTypes = types.Where(x => x.IsClass).ToArray();
            var interfaceTypes = types.Where(x => x.IsInterface).ToArray();
            foreach (var implementType in implementTypes)
            {
                var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
                if (interfaceType != null)
                {
                    //if (interfaceType == typeof(IContentRepository)) continue;

                    services.AddScoped(interfaceType, implementType);
                }
            }
            return services;
        }
    }
}
